package wechat

import (
	"context"
	"github.com/go-pay/gopay/wechat/v3"
	"github.com/spf13/viper"
	v1 "golang-sgg-daijia/api/v1"
	"golang-sgg-daijia/pkg/log"
	"net/http"
)

type WeChatPayClient interface {
	Prepay(ctx context.Context, amount int64, orderNo, content, customerOpenID string) (*v1.WxPrepayVo, error)
	QueryPayStatus(ctx context.Context, orderNo string)  (*wechat.QueryOrder, error)
	Notify(ctx context.Context, request *http.Request) (*wechat.QueryOrder,error)
}

type weChatPayClient struct {
	wxPay *wechat.ClientV3
	logger *log.Logger
	conf *viper.Viper
}

func NewWeChatPayCli(
	wxPay *wechat.ClientV3,
	logger *log.Logger,
	conf *viper.Viper,
) WeChatPayClient {
	return &weChatPayClient{
		wxPay: wxPay,
		logger: logger,
		conf: conf,
	}
}

func NewWeChatPay(conf *viper.Viper) *wechat.ClientV3 {
	//mchID := conf.GetString("security.wx.mch_id") // 商户号
	//mchCertificateSerialNumber := conf.GetString("security.wx.mch_certificate_serial_number") // 商户证书序列号
	//mchAPIv3Key := conf.GetString("security.wx.mch_APi_V3_key") // 商户APIv3密钥
	//
	//// 该为使用gopay库
	//mchPrivateKeyStr, err := os.ReadFile(conf.GetString("security.wx.private_key_path"))
	//if err != nil {
	//	panic(err)
	//}
	//client, err := wechat.NewClientV3(mchID, mchCertificateSerialNumber, string(mchPrivateKeyStr), mchAPIv3Key)
	//if err != nil {
	//	panic(err)
	//}
	//err = client.AutoVerifySign()
	var client *wechat.ClientV3
	return client
}

func (w *weChatPayClient) Prepay(ctx context.Context, amount int64, orderNo, content, customerOpenID string) (*v1.WxPrepayVo, error) {

	//expire := time.Now().Add(10 * time.Minute).Format(time.RFC3339)
	//// 初始化 BodyMap
	//bm := make(gopay.BodyMap)
	//bm.Set("sp_appid", w.conf.GetString("security.wx.app_id")).
	//	Set("sp_mchid", w.conf.GetString("security.wx.mch_id")).
	//	Set("description", content).
	//	Set("out_trade_no", orderNo).
	//	Set("time_expire", expire).
	//	Set("notify_url", w.conf.GetString("security.wx.notify_url")).
	//	SetBodyMap("amount", func(bm gopay.BodyMap) {
	//		bm.Set("total", amount).
	//			Set("currency", "CNY")
	//	}).
	//	SetBodyMap("payer", func(bm gopay.BodyMap) {
	//		bm.Set("sp_openid", customerOpenID)
	//	}).
	//	SetBodyMap("settle_info", func(bm gopay.BodyMap) {
	//		bm.Set("ProfitSharing", true)
	//	})
	//
	//wxRsp, err := w.wxPay.V3TransactionJsapi(ctx, bm)
	//if err != nil {
	//	w.logger.WithContext(ctx).Error("weChatPayClient|Prepay", zap.Error(err))
	//	return nil, err
	//}
	//if wxRsp.Code != 200 {
	//	return nil, v1.ErrInternalServerError
	//}
	//jsapi, err := w.wxPay.PaySignOfJSAPI(w.conf.GetString("security.wx.app_id"), wxRsp.Response.PrepayId)
	//
	//// GO 的SDK和Java的不太一样，研究了好一会儿没整清楚，换了gopay库
	//return &v1.WxPrepayVo{
	//	AppId:     jsapi.AppId,
	//	NonceStr:  jsapi.NonceStr,
	//	Package:   jsapi.Package,
	//	PaySign:   jsapi.PaySign,
	//	SignType:  jsapi.SignType,
	//	TimeStamp: jsapi.TimeStamp,
	//}, nil

	return &v1.WxPrepayVo{
		AppId:     "jsapi.AppId",
		NonceStr:  "jsapi.NonceStr",
		Package:   "jsapi.Package",
		PaySign:   "jsapi.PaySign",
		SignType:  "jsapi.SignType",
		TimeStamp: "jsapi.TimeStamp",
	}, nil

}

func (w *weChatPayClient) QueryPayStatus(ctx context.Context, orderNo string) (*wechat.QueryOrder, error) {
	//rsp, err := w.wxPay.V3TransactionQueryOrder(ctx, wechat.OutTradeNo, orderNo)
	//if err != nil {
	//	w.logger.WithContext(ctx).Error("weChatPayClient|QueryPayStatus", zap.Error(err))
	//	return false, err
	//}
	//if rsp.Code != 0 {
	//	return false, v1.ErrInternalServerError
	//}
	//return rsp.Response.TradeState == gopay.SUCCESS, nil
	//return rsp.Response, nil

	return &wechat.QueryOrder{
		TransactionId: "123",
		OutTradeNo: orderNo,
	}, nil
}

func (w *weChatPayClient) V3DecryptText() {

}

func (w *weChatPayClient) Notify(ctx context.Context, request *http.Request) (*wechat.QueryOrder,error) {
	//notifyReq, err := wechat.V3ParseNotify(request)
	//if err != nil {
	//	w.logger.WithContext(ctx).Error("weChatPayClient|Notify", zap.Error(err))
	//	return nil, err
	//}
	//// 获取微信平台证书
	//certMap := w.wxPay.WxPublicKeyMap()
	//// 验证异步通知的签名
	//err = notifyReq.VerifySignByPKMap(certMap)
	//if err != nil {
	//	w.logger.WithContext(ctx).Error("weChatPayClient|Notify", zap.Error(err))
	//	return nil, err
	//}
	//transaction := &wechat.QueryOrder{}
	//err = notifyReq.DecryptCipherTextToStruct(w.conf.GetString("wxpay.api_v3_key"), transaction)
	//return transaction, nil

	orderNo := request.Header.Get("orderNo")
	return &wechat.QueryOrder{
		TransactionId: "123",
		OutTradeNo: orderNo,
	}, nil
}

